package com.maxmlr.framework.mybatisplus.result;

import com.google.common.collect.Lists;
import com.maxmlr.framework.mybatisplus.config.Configuration;
import com.maxmlr.framework.mybatisplus.mapper.MapperData;
import lombok.AllArgsConstructor;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @ClassName DefaultResultHandler
 * @Description TODO
 * @Author maxiao
 * @Date 2020/3/23 下午2:31
 * @Version V1.0
 */
@AllArgsConstructor
public class ResultSetHandler {

    private Configuration configuration;

    public <T> List<T> handle(PreparedStatement pstmt, MapperData<T> mapperData) throws SQLException, IllegalAccessException, InstantiationException {
        List<T> resultList = Lists.newArrayList();
        Class<T> type = mapperData.getType();
        Field[] fields = type.getDeclaredFields();
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            T t = type.newInstance();
            for (Field field : fields) {
                com.maxmlr.framework.mybatisplus.annotation.Field annotation = field.getAnnotation(com.maxmlr.framework.mybatisplus.annotation.Field.class);
                String value = annotation.value();
                if ("".equals(value)) {
                    value = field.getName();
                }
                Object object = rs.getObject(value);
                field.setAccessible(true);
                field.set(t, object);
            }
            resultList.add(t);
        }
        return resultList;
    }
}
